package com.jackrain.nea.ext.permission;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.core.redis.CusRedisTemplate;
import com.jackrain.nea.core.schema.Table;
import com.jackrain.nea.core.schema.TableManager;
import com.jackrain.nea.core.webaction.WebAction;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.utility.StringUtil;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.QuerySession;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;

/**
 * @author lzm
 * 使用入口
 */
@Slf4j
public class Permissions {
    private static MenuCollection menTree = null;
    private static MenuCollection menTreeInDevMode = null;
    public static String MENU_TREE_REDIS_KEY = "__menuTree";
    public static String MENU_TREE_IN_DEV_REDIS_KEY = "__menuTree_inDev";
    public static String GROUP_MENU_PERMISSION_REDIS_KEY = "__menuPermission";
    public static String USER_PERMISSION_KKEY = "__userPermissions";
    /**
     * redis敏感列权限key
     */
    public static final String COLUMN_PERMISSION_KEY = "__COLUMN_PERMISSION";

    /**
     * 品牌权限Key
     */
    public static final String BRAND_PERMISSION_KEY = "__BRAND_PERMISSION";


    public static final String COLUMN_LIST_KEY = "__COLUMN_LIST";
    /**
     * 配销中心权限key
     */
    public static final String DISTRIB_PERMISSION_KEY = "__DISTRIB_PERMISSION";

    /**
     * 店仓制单主店仓key
     */
    public static final String MAIN_STORE_PERMISSION_KEY = "__MAIN_STORE_PERMISSION";

    /**
     * 店仓制单关联店仓key
     */
    public static final String RELATION_STORE_PERMISSION_KEY = "__RELATION_STORE_PERMISSION";


    private static Map<String, String> dataPermissionColumnMap = new HashMap<>();

    static {
        //品牌数据权限
        dataPermissionColumnMap.put("PS_C_BRAND_ID", BRAND_PERMISSION_KEY);
        //配销中心数据权限
        dataPermissionColumnMap.put("CP_C_DISTRIB_ID", DISTRIB_PERMISSION_KEY);
        //店仓制单关联店仓
        dataPermissionColumnMap.put("CP_C_RELATION_STORE_ID", RELATION_STORE_PERMISSION_KEY);
        //店仓制单主店仓
        dataPermissionColumnMap.put("CP_C_MAIN_STORE_ID", MAIN_STORE_PERMISSION_KEY);
    }

    /**
     * 获取菜单树（未按权限过滤）
     */
    public static MenuCollection getMenuTree() {
        return getMenuTree(false);
    }

    /**
     * 获取菜单树（未按权限过滤）,可强行刷新
     */
    public static MenuCollection getMenuTree(boolean forceReload) {
        if (forceReload || menTree == null) {
            CusRedisTemplate<String, MenuCollection> redisTemplate = RedisOpsUtil.getObjRedisTemplate();
            menTree = redisTemplate.opsForValue().get(MENU_TREE_REDIS_KEY);
        }
        return menTree;
    }

    public static MenuCollection getMenuTreeInDevMode(boolean forceReload) {
        if (forceReload || menTreeInDevMode == null) {
            CusRedisTemplate<String, MenuCollection> redisTemplate = RedisOpsUtil.getObjRedisTemplate();
            menTreeInDevMode = redisTemplate.opsForValue().get(MENU_TREE_IN_DEV_REDIS_KEY);
        }
        return menTreeInDevMode;
    }

    public static void setMenuTree(MenuCollection newValue) {
        menTree = newValue;
    }

    public static void setMenuTreeInDevMode(MenuCollection newValue) {
        menTreeInDevMode = newValue;
    }

    /**
     * 获取菜单树（摘掉根节点，未按权限过滤）
     */
    public static Collection<MenuNode> getAllMenus(boolean forceReload) {
        ArrayList<MenuNode> result = new ArrayList<>();
        result.add(getMenuTree(forceReload).getRootNode());
        return result;
    }

    /**
     * 获取菜单树（摘掉根节点，未按权限过滤）
     */
    public static Collection<MenuNode> getAllMenusInDevMode(boolean forceReload) {
        return getMenuTreeInDevMode(forceReload).getRootNode().getChildren();
    }

    /**
     * 根据用户获取权限集合
     */
    public static PermissionCollection getPermissionsByUser(QuerySession session) {
        if (session == null) {
            return new PermissionCollection();
        }
        User user = session.getUser();
        if (user == null) {
            return new PermissionCollection();
        }
        PermissionCollection result = doGetPermissionsByUser(session);
        if (user.isDev()) {
            return new InDevPermissionCollection(getMenuTreeInDevMode(false), result);
        }
        return result;
    }

    private static PermissionCollection doGetPermissionsByUser(QuerySession session) {
        User user = session.getUser();
        String userId = String.valueOf(user.getId());
        if (user.isAdmin()) {
            return new AdminPermissionCollection(session.getTableManager(), getMenuTree());
        }
        CusRedisTemplate<String, Object> redisTemplate = RedisOpsUtil.getObjRedisTemplate();
        PermissionCollection result = (PermissionCollection) redisTemplate.opsForHash().get(USER_PERMISSION_KKEY, userId);
        if (result == null) {
            log.warn("还没往填充session中填充用户的权限对象呢");
            return new PermissionCollection();
        }
        return result;
    }

    /**
     * 获取当前用户的菜单树（摘掉根节点，已按权限过滤）
     */
    public static Collection<MenuNode> getMenusFilterByUser(QuerySession session) {
        PermissionCollection permissions = getPermissionsByUser(session);
        return getMenusFilterByPermissions(permissions);
    }

    public static Collection<JSONObject> getActionsFilterByUser(QuerySession session, TableManager tm, MenuType type, Long tmId) {
        PermissionCollection permissions = getPermissionsByUser(session);
        return getActionsFilterByPermissions(session.getLocale(), tm, permissions, type, tmId);
    }

    public static Collection<JSONObject> getActionsFilterByPermissions(Locale locale, TableManager tm, PermissionCollection rights, MenuType type, Long tmId) {
        MenuCollection tree = getMenuTreeInDevMode(false);

        MenuNode node = tree.fetchByTmId(type, tmId);
        if (node == null && type == MenuType.TABLE) {
            node = tree.fetchAliasActionByTable(tmId);
        }
        Collection<Long> subActions;
        if (node != null) {
            subActions = tree.fetchActions(node.getId(), null);
        } else {
            if (type == MenuType.TABLE) {
                throw new NDSException(String.format("表%s:未配置对应的菜单项！哪来的下挂的动作定义！", tmId));
            }
            subActions = tree.fetchActions(null, tmId);
        }
        Collection<JSONObject> result = Lists.newArrayList();
        subActions.forEach(actionId -> {
            ActionPermissionModel actionRight = rights.fetchActionById(actionId);
            if (actionRight != null && actionRight.getPermission() > 0) {
                WebAction subAction = tm.getWebAction(actionId.intValue());
                if (subAction != null) {
                    result.add(subAction.toObj(locale, null));
                }
            }
        });
        return result;
    }

    /**
     * 获取菜单树（摘掉根节点，已按权限过滤）
     */
    public static Collection<MenuNode> getMenusFilterByPermissions(PermissionCollection unionedCollection) {
        MenuNode root = getMenuTreeInDevMode(false).getRootNode();
        MenuNode newRoot = root.copy();
        for (MenuNode child : root.getChildren()) {
            doCreateNode(unionedCollection, newRoot, child);
        }
        return newRoot.getChildren();
    }

    private static void doCreateNode(PermissionCollection unionedCollection, MenuNode newParentNode, MenuNode oldNode) {
        MenuNode newNode = oldNode.copy();
        if (MenuNode.isRootNode(newNode) || newNode.getNodeType() == MenuNodeType.SUB_SYSTEM || newNode.getNodeType() == MenuNodeType.TABLE_CATEGORY) {
            for (MenuNode oldChildNode : oldNode.getChildren()) {
                doCreateNode(unionedCollection, newNode, oldChildNode);
            }
        }
        if (newNode.getNodeType() == MenuNodeType.MENU) {
            MenuPermissionModel model = unionedCollection.fetchMenuByMenuId(newNode.getId());
            if (model != null && model.getPermission() > 0) {
                newParentNode.getChildren().add(newNode);
            }
        } else {
            if (newNode.getChildren().size() > 0) {
                newParentNode.getChildren().add(newNode);
            }
        }
    }

    /**
     * 先序遍历菜单项（工具方法）
     */
    public static void traversePreOrder(MenuNode node, Function<MenuNode, Object> nodeProcessor, Function<MenuNode, Boolean> needTraveseChildren) {
        if (node == null) {
            return;
        }
        //rootNode的标志就是id=-1
        if (!MenuNode.isRootNode(node)) {
            nodeProcessor.apply(node);
        }
        if (MenuNode.isRootNode(node) || needTraveseChildren == null || needTraveseChildren.apply(node)) {
            for (MenuNode childNode : node.getChildren()) {
                traversePreOrder(childNode, nodeProcessor, needTraveseChildren);
            }
        }
    }

    /**
     * 获取权限集合（按组来获取）
     */
    public static PermissionCollection getPermissionCollection(Long groupId) {
        CusRedisTemplate<String, Object> template = RedisOpsUtil.getObjRedisTemplate();
        PermissionCollection coll = (PermissionCollection) template.opsForHash().get(GROUP_MENU_PERMISSION_REDIS_KEY, groupId.toString());
        if (coll == null) {
            coll = PermissionCollection.createEmptyCollection();
        }
        return coll;
    }

    /**
     * 获取菜单权限列表（按菜单树排序，如某菜单项无权限也需构造一个空权限对象出来）
     */
    public static List<MenuPermissionModel> getMenuPermissionsWithDefault(Long groupId, Long subSystemId, Long tableCategoryId) {
        PermissionCollection rights = getPermissionCollection(groupId);
        MenuCollection tree = getMenuTree(true);
        if (tree == null) {
            return Collections.emptyList();
        }
        MenuNode node;
        if (tableCategoryId != null && tableCategoryId > 0) {
            node = tree.fetchById(MenuNodeType.TABLE_CATEGORY, tableCategoryId);
        } else if (subSystemId != null && subSystemId > 0) {
            node = tree.fetchById(MenuNodeType.SUB_SYSTEM, subSystemId);
        } else {
            node = tree.getRootNode();
        }

        List<MenuPermissionModel> result = new ArrayList<>();
        traversePreOrder(node, child -> {
            if (child.getNodeType() == MenuNodeType.MENU) {
                result.add(rights.fetchMenuOrDefault(child, groupId));
            }
            return null;
        }, child -> child.getNodeType() == MenuNodeType.SUB_SYSTEM || child.getNodeType() == MenuNodeType.TABLE_CATEGORY);
        return result;
    }

    /**
     * 获取动作定义权限列表（按动作定义排序，如某动作定义无权限也需构造一个空权限对象出来）
     */
    public static Collection<ActionPermissionModel> getActionPermissionsWithDefault(QuerySession session, Long groupId, Long menuId) {
        MenuCollection tree = getMenuTree(true);
        TableManager tm = session.getTableManager();
        PermissionCollection rights = getPermissionCollection(groupId);
        Collection<Long> actionIds = tree.fetchActions(menuId, null);

        ArrayList<ActionPermissionModel> result = new ArrayList<>();
        String format = Resources.getMessage("%d对应的WebAction不存在！");
        for (Long actionId : actionIds) {
            WebAction action = tm.getWebAction(actionId.intValue());
            if (action == null) {
                log.warn(String.format(format, action));
                continue;
            }
            ActionPermissionModel permissionModel = rights.fetchActionOrDefault(tm, tree, action, groupId);
            Collection<Long> childActionIds = tree.fetchActions(null, actionId);
            Collection<ActionPermissionModel> childPermissions = new ArrayList<>();
            for (Long childActionId : childActionIds) {
                WebAction childAction = tm.getWebAction(childActionId.intValue());
                if (childAction == null) {
                    log.warn(String.format(format, childAction));
                    continue;
                }
                ActionPermissionModel childPermissionModel = rights.fetchActionOrDefault(tm, tree, childAction, groupId);
                childPermissions.add(childPermissionModel);
            }
            permissionModel.setChildren(childPermissions);
            result.add(permissionModel);
        }
        return result;
    }

    /**
     * 获取当前用户 在某个表、动作定义中的权限值
     */
    public static int getPermission(QuerySession session, MenuType type, Long tmId) {
        PermissionCollection rights = getPermissionsByUser(session);
        MenuCollection tree = getMenuTreeInDevMode(false);
        MenuNode node = tree.fetchByTmId(type, tmId);
        log.debug(String.format("getPermission-start:{user:%d, type:%s, tmId:%d}", session.getUser().getId(), type.getDesc(), tmId));
        if (node == null && type == MenuType.TABLE) {
            log.debug(String.format("getPermission-findAliasAction:{user:%d, type:%s, tmId:%d}", session.getUser().getId(), type.getDesc(), tmId));
            node = tree.fetchAliasActionByTable(tmId);
        }
        if (node == null) {
            log.debug(String.format("getPermission-is not menu:{user:%d, type:%s, tmId:%d}", session.getUser().getId(), type.getDesc(), tmId));
            if (type == MenuType.ACTION) {
                //动作定义
                log.debug(String.format("getPermission-is a action:{user:%d, type:%s, tmId:%d}", session.getUser().getId(), type.getDesc(), tmId));
                ActionPermissionModel model = rights.fetchActionById(tmId);
                if (model != null) {
                    log.debug(String.format("getPermission-result:{user:%d, type:%s, tmId:%d,permission:%d}", session.getUser().getId(), type.getDesc(), tmId, model.getPermission()));
                    return model.getPermission();
                }
            }
            return 0;
        }
        log.debug(String.format("getPermission-is a menu:{user:%d, type:%s, tmId:%d}", session.getUser().getId(), type.getDesc(), tmId));
        MenuPermissionModel model = rights.fetchMenuByMenuId(node.getId());
        if (model != null) {
            log.debug(String.format("getPermission-result:{user:%d, type:%s, tmId:%d, permission:%d}", session.getUser().getId(), type.getDesc(), tmId, model.getPermission()));
            return model.getPermission();
        }
        return 0;
    }

    /**
     * 获取当前用户 在某个表、动作定义中的权限值(只获取部分感兴趣的权限)
     */
    public static int getPermission(QuerySession session, MenuType type, Long tmId, String mask) {
        int permission = getPermission(session, type, tmId);
        return permission & TableMaskHelper.fromNewMaskString(mask);
    }

    /**
     * 获取当前用户 在某个表、动作定义中的权限值(只获取部分感兴趣的权限)
     */
    public static int getPermission(QuerySession session, MenuType type, Long tmId, int mask) {
        int permission = getPermission(session, type, tmId);
        return permission & mask;
    }

    /**
     * 检查当前用户对某个表、动作定义是否有某种权限值(多个mask值)
     */
    public static boolean hasPermission(QuerySession session, MenuType type, Long tmId, int mask) {
        log.debug(String.format("hasPermission:{user:%d, type:%s, tmId:%d, mask:%d}", session.getUser().getId(), type.getDesc(), tmId, mask));
        int permission = getPermission(session, type, tmId, mask);
        return permission == mask;
    }

    /**
     * 检查当前用户对某个表、动作定义是否有某种权限值(多个mask值)
     */
    public static boolean hasPermission(QuerySession session, MenuType type, Long tmId, String mask) {
        return hasPermission(session, type, tmId, TableMaskHelper.fromNewMaskString(mask));
    }

    /**
     * 获取读权限互斥集合（已去重）
     *
     * @param user
     * @return
     * @Author: yangxy
     * @Date: 15:02 2017-12-15
     */
    public static List<String> getUnReadableColumns(User user) {
        List<String> result = Lists.newArrayList();
        if (user.isAdmin()) {
            return result;
        }
        List<Long> groupsIds = user.getGroups();

        List<String> left = Lists.newArrayList();
        if (null != groupsIds && groupsIds.size() > 0) {
            Map<String, ColumnPermission> rMaps = Maps.newHashMap();
            Map<String, ColumnPermission> maps = getAllColumns(groupsIds);
            //获取读权限
            for (String key : maps.keySet()) {
                if ("Y".equals(maps.get(key).getIsRead())) {
                    rMaps.put(key, maps.get(key));
                }
            }
            List<ColumnEntity> columnEntities = getColumnList();
            Map<String, ColumnEntity> sourceMaps = Maps.newHashMap();
            for (ColumnEntity col : columnEntities) {
                sourceMaps.put(col.getEcode(), col);
            }
            Map<String, ColumnEntity> resultMaps = Maps.newHashMap();
            for (String sourceKey : sourceMaps.keySet()) {
                for (String key : rMaps.keySet()) {
                    if (sourceKey.equals(key)) {
                        resultMaps.put(sourceKey, sourceMaps.get(sourceKey));
                        break;
                    }
                }
            }
            //返回互斥
            left = Lists.newArrayList(Maps.difference(sourceMaps, resultMaps).entriesOnlyOnLeft().keySet());
        }

        for (String temp : left) {
            if (temp != null) {
                String[] arr = temp.split(";");
                for (int i = 0; i < arr.length; i++) {
                    String isTrim = arr[i].trim();
                    if (!Strings.isNullOrEmpty(isTrim)) {
                        result.add(isTrim);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 获取写权限互斥集合（已去重）
     *
     * @param user
     * @return
     * @Author: yangxy
     * @Date: 15:02 2017-12-15
     */
    public static List<String> getUnWritableColumns(User user) {
        List<String> result = Lists.newArrayList();
        if (user.isAdmin()) {
            return result;
        }
        List<Long> groupsIds = user.getGroups();

        List<String> left = Lists.newArrayList();
        if (null != groupsIds && groupsIds.size() > 0) {
            Map<String, ColumnPermission> wMaps = Maps.newHashMap();
            Map<String, ColumnPermission> maps = getAllColumns(groupsIds);
            for (String key : maps.keySet()) {
                if ("Y".equals(maps.get(key).getIsModify())) {
                    wMaps.put(key, maps.get(key));
                }
            }
            List<ColumnEntity> columnEntities = getColumnList();
            Map<String, ColumnEntity> sourceMaps = Maps.newHashMap();
            for (ColumnEntity col : columnEntities) {
                sourceMaps.put(col.getEcode(), col);
            }
            Map<String, ColumnEntity> resultMaps = Maps.newHashMap();
            for (String sourceKey : sourceMaps.keySet()) {
                for (String key : wMaps.keySet()) {
                    if (sourceKey.equals(key)) {
                        resultMaps.put(sourceKey, sourceMaps.get(sourceKey));
                        break;
                    }
                }
            }
            left = Lists.newArrayList(Maps.difference(sourceMaps, resultMaps).entriesOnlyOnLeft().keySet());
        }
        for (String temp : left) {
            if (temp != null) {
                String[] arr = temp.split(";");
                for (int i = 0; i < arr.length; i++) {
                    String isTrim = arr[i].trim();
                    if (!Strings.isNullOrEmpty(isTrim)) {
                        result.add(isTrim);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 获取读写权限（去重）
     *
     * @param groupsIds
     * @Author: yangxy
     * @Date: 9:52 2017-12-18
     */
    public static Map<String, ColumnPermission> getAllColumns(Collection<Long> groupsIds) {
        //结果集合
        Map<String, ColumnPermission> sourceMaps = Maps.newHashMap();
        for (Long gid : groupsIds) {
            //获取敏感权限
            List<ColumnPermission> targetList = getColumnPermissions(COLUMN_PERMISSION_KEY, gid.toString());
            Map<String, ColumnPermission> targetMaps = Maps.newHashMap();
            for (ColumnPermission item : targetList) {
                targetMaps.put(item.getEcode(), item);
            }
            MapDifference<String, ColumnPermission> difference = Maps.difference(sourceMaps, targetMaps);
            Map<String, ColumnPermission> rightDiffer = difference.entriesOnlyOnRight();
            Map<String, ColumnPermission> commonPart = difference.entriesInCommon();

            //合并集合,得到互斥差集
            for (String key : rightDiffer.keySet()) {
                sourceMaps.put(key, rightDiffer.get(key));
            }
            //判断isread,iswirte,合并集合
            for (String key : commonPart.keySet()) {
                ColumnPermission leftItem = sourceMaps.get(key);
                ColumnPermission rightItem = targetMaps.get(key);
                ColumnPermission mergedItem = merge(leftItem, rightItem);
                sourceMaps.put(key, mergedItem);
            }
        }
        return sourceMaps;
    }


    /**
     * 敏感列权限合并
     *
     * @param leftItem
     * @param rightItem
     * @return
     * @Author: yangxy
     * @Date: 10:34 2017-12-19
     */
    private static ColumnPermission merge(ColumnPermission leftItem, ColumnPermission rightItem) {
        if (null != leftItem) {
            if (null != rightItem.getIsRead() && "Y".equals(rightItem.getIsRead())) {
                leftItem.setIsRead("Y");
            }
            if (null != rightItem.getIsModify() && "Y".equals(rightItem.getIsModify())) {
                leftItem.setIsModify("Y");
            }
        } else {
            return rightItem;
        }

        return leftItem;
    }

    /**
     * 获取敏感列权限
     *
     * @param rawKey
     * @param rawHashKey
     * @Author: yangxy
     * @Date: 15:02 2017-12-15
     */
    private static List<ColumnPermission> getColumnPermissions(String rawKey, String rawHashKey) {
        CusRedisTemplate<String, JSONObject> redisTemplate = RedisOpsUtil.getObjRedisTemplate();
        List<ColumnPermission> list = (List<ColumnPermission>) redisTemplate.opsForHash().get(rawKey, rawHashKey);
        if (list == null) {
            return Lists.newArrayList();
        }
        return list;
    }

    /**
     * 获取敏感列定义
     *
     * @Author: yangxy
     * @Date: 19:10 2017-12-18
     */
    public static List<ColumnEntity> getColumnList() {
        CusRedisTemplate<String, JSONObject> redisTemplate = RedisOpsUtil.getObjRedisTemplate();
        List<ColumnEntity> list = (List<ColumnEntity>) redisTemplate.opsForHash().get(COLUMN_LIST_KEY, "1");
        if (list == null) {
            return Lists.newArrayList();
        }
        return list;
    }

    /**
     * @param columnName
     * @param hashKey
     * @Author: yangxy
     * @Date: 14:45 2018-3-9
     */
    private static Collection<DataPermissionModel> getDataPermissions(String columnName, Integer hashKey) {
        CusRedisTemplate<String, JSONObject> redisTemplate = RedisOpsUtil.getObjRedisTemplate();
        List<DataPermissionModel> list = null;
        String redisKey = dataPermissionColumnMap.get(columnName);
        if (redisKey == null || redisKey.isEmpty()) {
            throw new NDSException(String.format("列%s并不是数据权限列！请检查！", columnName));
        }
        list = (List<DataPermissionModel>) redisTemplate.opsForHash().get(redisKey, hashKey.toString());
        return list;
    }

    /**
     * 返回table中过滤权限
     * @param table
     */
    public static JSONArray filterDataPermissons(Table table){
        JSONObject tableProps = table.getJSONProps();
        return tableProps==null ? null:tableProps.getJSONArray("precolnames");
    }


    /**
     * @param columnName
     * @param userId
     * @Author: yangxy
     * @Date: 14:45 2018-3-9
     */
    public static List<Long> getReadableDatas(DataPermissionsType columnName, Integer userId) {
        return getReadableDatas(columnName.getKey(), userId);
    }

    /**
     * @param columnName
     * @param userId
     * @Author: yangxy
     * @Date: 14:45 2018-3-9
     */
    public static List<Long> getWritableDatas(DataPermissionsType columnName, Integer userId) {
        return getWritableDatas(columnName.getKey(), userId);
    }

    /**
     * @param columnName
     * @param hashKey
     * @Author: yangxy
     * @Date: 9:06 2017-12-25
     */
    public static List<Long> getReadableDatas(String columnName, Integer hashKey) {
        if (columnName == null) {
            throw new NDSException(String.format("数据权限列居然配成空值！请检查"));
        }
        columnName = columnName.toUpperCase();
        Collection<DataPermissionModel> dataPermissions = getDataPermissions(columnName, hashKey);
        List<Long> result = Lists.newArrayList();
        if (dataPermissions == null) {
            return result;
        }

        for (DataPermissionModel item : dataPermissions) {
            if ("Y".equalsIgnoreCase(item.getIsRead())) {
                result.add(item.getId());
            }
        }
        return result;
    }



    /**
     * @param columnName
     * @param hashKey
     * @Author: yangxy
     * @Date: 9:06 2017-12-25
     */
    public static List<Long> getWritableDatas(String columnName, Integer hashKey) {
        if (columnName == null) {
            throw new NDSException(String.format("数据权限列居然配成空值！请检查"));
        }
        columnName = columnName.toUpperCase();
        List<Long> result = Lists.newArrayList();
        Collection<DataPermissionModel> dataPermissions = getDataPermissions(columnName, hashKey);

        if (dataPermissions == null) {
            return result;
        }

        for (DataPermissionModel item : dataPermissions) {
            if ("Y".equalsIgnoreCase(item.getIsWrite())) {
                result.add(item.getId());
            } else if ("PS_C_BRAND_ID".equalsIgnoreCase(columnName) && "Y".equalsIgnoreCase(item.getIsRead())) {
                result.add(item.getId());
            }
        }
        return result;
    }

}
